package tt.dz.dao.base;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.PreparedStatementSetter;

import tt.dz.util.Constants;
import tt.dz.util.ReflectUtils;
import tt.dz.util.annotation.AnnotationUtils;
/**
 * 数据库基础操作类
 * @author pengyu
 */
public class BaseDao<T> extends BasisDao<T>{

	@Override
	public int LogicDeleteObject(Object obj) {
		
		return super.LogicDeleteObject(obj);
	}

	@Override
	public List<Map<String, Object>> findDataBySql(String sql, Object... params) {
		
		return super.findDataBySql(sql, params);
	}

	@Override
	public List<T> findDataBySqlOfClass(String sql, Class<?> cls, Object... params) {
		
		return super.findDataBySqlOfClass(sql, cls, params);
	}

	@Override
	public List<T> findExample(Object obj, Integer pageNo, Integer pageSize, String sortName, Integer sortVal) {
		
		return super.findExample(obj, pageNo, pageSize, sortName, sortVal);
	}

	@Override
	public List<T> findListByClass(Class<?> cls, ListOrderedMap paramsMap, Integer pageNo, Integer pageSize,
			String sortName, Integer sortVal) {
		
		return super.findListByClass(cls, paramsMap, pageNo, pageSize, sortName, sortVal);
	}

	@Override
	public int save(Object obj) {
		
		return super.save(obj);
	}

	@Override
	public int saveList(List<T> obj) {
		
		return super.saveList(obj);
	}

	@Override
	public int updateObject(Object obj) {
		int result = super.updateObject(obj);
		log.debug(result);
		return result;
	}


	/**log4j日志 */
	private static final Log log = LogFactory.getLog(BaseDao.class);

	@SuppressWarnings("unchecked")
	public T findOneExample(final Object obj,String order,String sortVal){

		//得到类信息
		Class<?> cls = obj.getClass();
		//所有属性
		Field fields[] =  cls.getDeclaredFields();
		//获取表名称
		String tableName = AnnotationUtils.getEntityTableMappingByAnnotationName(cls);

		StringBuffer buffer = new StringBuffer("SELECT ");
		buffer.append(ReflectUtils.setQueryColumn(fields, tableName));
		buffer.append(" FROM ");
		buffer.append(tableName);


		//是否首次追加条件
		boolean firstAppend = true;

		//参数值
		final List<Object> queryParamList = new ArrayList<Object>();
		//循环属性追加条件
		for (Field field : fields) {

			//判断是否含有不可用修饰符
			if(!ReflectUtils.judgeModifiersAvailable(field)){
				//是否为忽略映射属性
				if(!AnnotationUtils.ignore(field)){
					//调用get方法
					Object resultObj = ReflectUtils.invokeObjectReadMethodByFieldNameAndClass(obj, field.getName(), cls);
					if(resultObj!=null){

						//首次追加where条件
						if(firstAppend){
							firstAppend = false;
							buffer.append(" WHERE ");
						}
						else{

							buffer.append(" AND ");
						}
						buffer.append(field.getName());
						buffer.append("=?");
						//将参数值顺序保存至list
						queryParamList.add(resultObj);
					}
				}
			}
		}
		if(order!=null){
			buffer.append(" order by "+ order+" ");
			if(sortVal!=null){
				buffer.append(sortVal);
			}else{
				buffer.append(" asc ");
			}
		}

		if(Constants.Jdbc.SHOW_SQL){
			log.debug("[MyJDBCFrameWork]:"+buffer);
			log.debug("[param]:" + queryParamList);
			System.out.println("[MyJDBCFrameWork]:"+buffer);log.debug("SQL ==>: " + buffer);
			System.out.println("[param]:"+queryParamList);log.debug("[param]:" + queryParamList);
		}
		List<T>  list =  getJdbcTemplate().query(buffer.toString(), new PreparedStatementSetter() {

			@Override
			public void setValues(PreparedStatement ps) throws SQLException {

				//设置参数
				for (int i=0;i<queryParamList.size();i++) {
					Object obj = queryParamList.get(i);
					ps.setObject(i+1, obj);
				}
			}
		}, new BeanPropertyRowMapper<T>((Class<T>) cls));
		System.out.println("list.size()="+list.size());
		if(list.size()>0){
			return list.get(0);
		}
		return null;
	}	

	@SuppressWarnings("unchecked")
	public T findOneExampleByCondition(final Object obj,String condition){

		//得到类信息
		Class<?> cls = obj.getClass();
		//所有属性
		Field fields[] =  cls.getDeclaredFields();
		//获取表名称
		String tableName = AnnotationUtils.getEntityTableMappingByAnnotationName(cls);
//		log.info("cls = "+cls);
//		log.info("tableName = "+tableName);
//		log.info("condition = "+condition);
		
		StringBuffer buffer = new StringBuffer("SELECT ");
		buffer.append(ReflectUtils.setQueryColumn(fields, tableName));
		buffer.append(" FROM ");
		buffer.append(tableName);
		buffer.append(" "+condition); 
		//参数值
		final List<Object> queryParamList = new ArrayList<Object>();
		//循环属性追加条件
		if(Constants.Jdbc.SHOW_SQL){
			System.out.println("[MyJDBCFrameWork]:"+buffer);log.debug("SQL ==>: " + buffer);
			System.out.println("[param]:"+queryParamList);log.debug("[param]:"+queryParamList);
		}
		//		this.getJdbcTemplate().query

		List<T>  list =  getJdbcTemplate().query(buffer.toString(), new PreparedStatementSetter() {

			@Override
			public void setValues(PreparedStatement ps) throws SQLException {

				//设置参数
				for (int i=0;i<queryParamList.size();i++) {
					Object obj = queryParamList.get(i);
					ps.setObject(i+1, obj);
				}
			}
		}, new BeanPropertyRowMapper<T>((Class<T>) cls));
		if(list.size()>0){
			return list.get(0);
		}
		return null;
	}	

	public List<T> findListByConditionWithIgnore(final Object obj,String condition){

		//得到类信息
		Class<?> cls = obj.getClass();
		//所有属性
		Field fields[] =  cls.getDeclaredFields();
		//获取表名称
		String tableName = AnnotationUtils.getEntityTableMappingByAnnotationName(cls);

		StringBuffer buffer = new StringBuffer("SELECT ");
		buffer.append(ReflectUtils.setQueryColumnWithIgnore(fields, tableName));
		buffer.append(" FROM ");
		buffer.append(tableName);
		buffer.append(" "+condition); 
		if(Constants.Jdbc.SHOW_SQL){
			System.out.println("[MyJDBCFrameWork]:"+buffer);log.debug("SQL ==>: " + buffer);
		}
		List<T>  list =  getJdbcTemplate().query(buffer.toString(), new PreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement arg0) throws SQLException {
				

			}}, new BeanPropertyRowMapper<T>((Class<T>) cls));
		return list;
	}

	public List<T> findListByCondition(final Object obj,String condition){

		//得到类信息
		Class<?> cls = obj.getClass();
		//所有属性
		Field fields[] =  cls.getDeclaredFields();
		//获取表名称
		String tableName = AnnotationUtils.getEntityTableMappingByAnnotationName(cls);

		StringBuffer buffer = new StringBuffer("SELECT ");
		buffer.append(ReflectUtils.setQueryColumn(fields, tableName));
		buffer.append(" FROM ");
		buffer.append(tableName);
		buffer.append(" "+condition); 
		if(Constants.Jdbc.SHOW_SQL){
			System.out.println("[MyJDBCFrameWork]:" + buffer);
			log.debug("SQL ==>: " + buffer);
		}
		List<T>  list =  getJdbcTemplate().query(buffer.toString(), new PreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement arg0) throws SQLException {
				

			}}, new BeanPropertyRowMapper<T>((Class<T>) cls));
		return list;
	}	

	public List<T> findListByPageAndGroupAndOrderAndCondition(final Object obj,String condition,Integer pageNo, Integer pageSize,String sortName,Integer sortVal,String groupByStrs){

		//得到类信息
		Class<?> cls = obj.getClass();
		//所有属性
		Field fields[] =  cls.getDeclaredFields();
		//获取表名称
		String tableName = AnnotationUtils.getEntityTableMappingByAnnotationName(cls);

		StringBuffer sqlBuffer = new StringBuffer("SELECT ");
		sqlBuffer.append(ReflectUtils.setQueryColumn(fields, tableName));
		sqlBuffer.append(" FROM ");
		sqlBuffer.append(tableName);
		sqlBuffer.append(" "+condition); 

		//分组
		if(groupByStrs!=null && !"".equals(groupByStrs)){
			sqlBuffer.append(" GROUP BY ");
			//tableName（主表）表的排序条件
			sqlBuffer.append(" ");
			sqlBuffer.append(groupByStrs);
			sqlBuffer.append("  ");
		}

		//排序匹配
		if(sortName!=null && !"".equals(sortName)){
			sqlBuffer.append(" ORDER BY ");
			//tableName（主表）表的排序条件
			sqlBuffer.append(" ");
			sqlBuffer.append(sortName);
			sqlBuffer.append(" ");
			if(sortVal==1){
				sqlBuffer.append(" ASC");
			}
			else{
				sqlBuffer.append(" DESC");
			}
		}

		//分页查询匹配
		if(pageNo!=null && pageSize!=null && pageSize.intValue()!=0){
			sqlBuffer.append(" LIMIT ");
			sqlBuffer.append((pageNo-1)*pageSize);
			sqlBuffer.append(",");
			sqlBuffer.append(pageSize);
		}

		if(Constants.Jdbc.SHOW_SQL){
			log.debug("[MyJDBCFrameWork]:"+sqlBuffer);
		}
		List<T>  list =  getJdbcTemplate().query(sqlBuffer.toString(), new PreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement arg0) throws SQLException {
				

			}}, new BeanPropertyRowMapper<T>((Class<T>) cls));
		return list;
	}	


	@SuppressWarnings("unchecked")
	public List<T> findAll(final Object obj){

		//得到类信息
		Class<?> cls = obj.getClass();
		//所有属性
		Field fields[] =  cls.getDeclaredFields();
		//获取表名称
		String tableName = AnnotationUtils.getEntityTableMappingByAnnotationName(cls);

		StringBuffer buffer = new StringBuffer("SELECT ");
		buffer.append(ReflectUtils.setQueryColumn(fields, tableName));
		buffer.append(" FROM ");
		buffer.append(tableName);


		//是否首次追加条件
		boolean firstAppend = true;

		//参数值
		final List<Object> queryParamList = new ArrayList<Object>();
		if(Constants.Jdbc.SHOW_SQL)
		{
			System.out.println("[MyJDBCFrameWork]:" + buffer);log.debug("SQL ==>: " + buffer);
			System.out.println("[param]:"+queryParamList);log.debug("[param]:"+queryParamList);
		}
		return getJdbcTemplate().query(buffer.toString(), new PreparedStatementSetter() {

			@Override
			public void setValues(PreparedStatement ps) throws SQLException {

				//设置参数
				for (int i=0;i<queryParamList.size();i++) {
					Object obj = queryParamList.get(i);
					ps.setObject(i+1, obj);
				}
			}
		}, new BeanPropertyRowMapper<T>((Class<T>) cls));
	}	

	public Boolean exec(String sql){
		try {
			//			int kk = getJdbcTemplate().update(sql);
			int kk = getJdbcTemplate().update(sql, new PreparedStatementSetter()  {
				@Override
				public void setValues(PreparedStatement paramPreparedStatement) throws SQLException {}
			});
			if(kk>0){
				return true;
			}
			return false;
			//			return true;
		} catch (DataAccessException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public int execAndReturnNum(String sql){
		try {
			//			int kk = getJdbcTemplate().update(sql);
			int kk = getJdbcTemplate().update(sql, new PreparedStatementSetter()  {
				@Override
				public void setValues(PreparedStatement paramPreparedStatement) throws SQLException {}
			});
			
			return kk;
			//			return true;
		} catch (DataAccessException e) {
			e.printStackTrace();
			return 0;
		}
	}

}

